package com.brian.singleton.singleton;

/**
 * @program: architect
 * @author: Brian Huang
 * @create: 2019-05-30 21
 *
 * 在被调用的时候才创建
 * 缺点： 线程不安全
 *  加锁synchronized 可以保证线程安全，但一般加synchronized锁意味着有线程等待
 **/
public class Singleton懒汉式2 {

    private static Singleton懒汉式2 singleton懒汉式;


    //构造函数私有化
    private Singleton懒汉式2() {
        //防止java反射技术破解
        if(singleton懒汉式 != null){
            try {
                throw new Exception("该对象已经被实例化。。。。");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public synchronized static Singleton懒汉式2 getSingleton懒汉式() {

        if(singleton懒汉式 == null){
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            singleton懒汉式 = new Singleton懒汉式2();
            return singleton懒汉式;
        }
        return singleton懒汉式;
    }

    public static void main(String[] args) {
       /* Singleton懒汉式 singleton懒汉式1 = Singleton懒汉式.getSingleton懒汉式();
        Singleton懒汉式 singleton懒汉式2 = Singleton懒汉式.getSingleton懒汉式();
        System.out.println(singleton懒汉式1 == singleton懒汉式2);*/

        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Singleton懒汉式2 singleton懒汉式1 = Singleton懒汉式2.getSingleton懒汉式();
                    System.out.println(Thread.currentThread().getName() + singleton懒汉式1);
                }
            }).start();

        }
    }
}
